package com.example.demo.controller.admin;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.StudentMap;
import com.example.demo.mapper.TeacherMap;
import com.example.demo.mapper.UserMap;
import com.example.demo.po.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMap userMap;

    @Autowired
    TeacherMap teacherMap;

    @Autowired
    StudentMap studentMap;

    @Autowired
    UserService userService;

    @GetMapping("/delete")
    public Result DeleteUser(@RequestParam("id") int id,@RequestParam("role") String role){

            if(role.equals("admin")||role.equals("teacher")){
               teacherMap.DeleteByUserId(id);
            }else {
                studentMap.DeleteByUserId(id);
            }
            userMap.DeleteUserById(id);

        return ResultUtil.success("删除成功!");
    }

    @GetMapping("/get")
    public Result GetUser(){



        return ResultUtil.success(userMap.GetUserList());
    }


    @PostMapping("/update")
    public Result UpdateUser(@RequestBody User user){


     Result result =  userService.UpdateUser(user);

        return result;
    }


    @GetMapping("/search")
    public Result searchUser(@RequestParam("name")String name,@RequestParam("role")String role){
        if(StringUtils.isEmpty(name)&&StringUtils.isEmpty(role)){
            return ResultUtil.success(  userMap.GetUserList()) ;

        }

        if(!StringUtils.isEmpty(name)&& !StringUtils.isEmpty(role)){
            return   ResultUtil.success( userMap.SearchUserListByALL("%"+name+"%",role)) ;
        }else if(!StringUtils.isEmpty(name)){
            return ResultUtil.success( userMap.SearchUserListByName("%"+name+"%")) ;
        }else {
            return ResultUtil.success( userMap.SearchUserListByRole(role)) ;
        }
    }


    @GetMapping("/getcount")
    @ResponseBody
    public Result GetCount(){
        int user1 =   userMap.CountTeacher();
        int user2 =   userMap.CountStudent();
        int[] list = new int[2];
        list[0] = user1;
        list[1] = user2;

        return ResultUtil.success(list);
    }


    @GetMapping("/getimg/{id}")
    public Result GetImg(@PathVariable int id){
         String path = userMap.GetUserAvatar(id);
        if(path==null||path.isEmpty()){
            return ResultUtil.success("");
        }

        return ResultUtil.success(userMap.GetUserAvatar(id));
    }



}
